<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      title="登录"
    >
      <van-icon
        slot="left"
        name="cross"
        @click="$router.back()"
      />
    </van-nav-bar>
    <!-- /导航栏 -->

    <van-form ref="loginForm" @submit="onSubmit">
      <van-field
        v-model="user.user_name"
        name="user_name"
        placeholder="请输入用户名"
        :rules="userFormRules.user_name"
        type="text"
        maxlength="10"
      >
        <i slot="left-icon" class="toutiao toutiao-shouji"></i>
      </van-field>
      <van-field
        v-model="user.password"
        name="password"
        placeholder="请输入密码"
        :rules="userFormRules.code"
        type="password"
        maxlength="6"
      >
        <i slot="left-icon" class="toutiao toutiao-yanzhengma"></i>
      </van-field>
      <div class="login-btn-wrap">
        <van-button class="login-btn" block type="info" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <!-- /登录表单 -->
  </div>
</template>

<script>
import { login } from '@/api/user'

export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        user_name: 'admin7',
        password: '123456'
      },
      userFormRules: {
        user_name: [{
          required: true,
          message: '用户不能为空'
        }, {
          pattern: /^[0-9a-zA-Z_]{1,10}$/,
          message: '用户名格式错误'
        }],
        password: [{
          required: true,
          message: '密码不能为空'
        }, {
          pattern: /^[0-9a-zA-Z_]{1,10}$/,
          message: '密码格式错误'
        }]
      }
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onSubmit () {
      // 1. 展示登陆中 loading
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
      })

      // 2. 请求登录
      try {
        const { data } = await login(this.user)
        console.log(data.meta)
        if (data.meta.status === 200) {
          this.$store.commit('setUser', data.data)
          this.$toast.success(data.meta.msg)
        } else {
          this.$toast.fail(data.meta.msg)
        }

        // 登录成功，跳转回原来页面
        this.$router.back()
      } catch (err) {
        if (err.meta.status === 400) {
          this.$toast.fail('错误')
        } else {
          this.$toast.fail('登录失败，请稍后重试')
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.login-container {
  .toutiao {
    font-size: 37px;
  }

  .send-sms-btn {
    width: 152px;
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 22px;
    color: #666;
  }

  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #e70201;
      border: none;
    }
  }
}
</style>
